//index.js
//获取应用实例
const app = getApp()
let startTime = 0;
Page({
  data: {
    demoList: [ // 这里id用途为计算列表项的位置
      { id: 0, name: 'react' },
      { id: 1, name: 'vue' },
      { id: 2, name: 'jquery' },
      { id: 3, name: 'amazeui' },
      { id: 4, name: 'weui' },
      { id: 5, name: 'mpvue' },
      { id: 6, name: 'wepy' },
      { id: 7, name: 'javascript' },
      { id: 8, name: 'css' },
      { id: 9, name: 'html' },
      { id: 10, name: '阿里巴巴' },
      { id: 11, name: '腾讯' },
      { id: 12, name: '百度' },
      { id: 13, name: '小米' },
      { id: 14, name: '华为' },
      { id: 15, name: '三星' },
      { id: 16, name: 'apple' },
      { id: 17, name: '魅族' },
    ],
    y0: 0,
    selectId: -1, //选中的id
    itemHeihgt: 60, // 每个列表项的高度
  },

  onLoad: function () {
  },

  //触摸开始
  movestart: function (e) {
    let id = e.currentTarget.dataset.id;
    startTime = e.timeStamp;
    wx.vibrateShort({ success: function () { console.log("振动成功") } });
    this.setData({ selectId: id });
  },
  
  //拖拽中
  onChange: function (e) {
    this.setData({ y0: e.detail.y });
  },

  //触摸结束
  moveend: function (e) {
    console.log("拖拽结束");
    wx.vibrateShort({ success: function () { console.log("振动成功") } });
    this.setData({ selectId: -1 });
    let t0 = e.timeStamp - startTime; //触摸时间
    let id = e.currentTarget.dataset.id;
    let demoList = this.data.demoList,
      itemHeihgt = this.data.itemHeihgt;
    let dataOne = demoList[id];
    let y0 = this.data.y0;
    let y0_i = parseInt(y0 / itemHeihgt);
    let y1 = id * itemHeihgt - y0; // 根据被移动元素原来和移动后的位置判断是向上还是向下移动
    if (y0 != 0 && (y1 > itemHeihgt || y1 < -itemHeihgt) && t0 > 260) { 
      // y0为零时说明元素被移到最顶，此时我认为该为移动无效.
      demoList.splice(id, 1);
      if (y1 < 0) { //向下移动
        demoList.splice(y0_i, 0, dataOne);
      } else if (y1 > 0) { //向上移动
        demoList.splice(y0_i + 1, 0, dataOne);
      }
      console.log("移动成功");
    }
    demoList.map((item, index) => {
      item.id = index;
    });
    this.setData({ demoList });
    let _this = this;
    setTimeout(function () {  //在onChange函数结束后清除y0
      _this.setData({ y0: 0 });
    }, 100)
  },

  //置顶
  toUpFun: function (e) {
    let tid = e.currentTarget.dataset.tid;
    let demoList = this.data.demoList;
    let dataOne = demoList[tid];
    demoList.splice(tid, 1);
    demoList.splice(0, 0, dataOne);
    demoList.map((item, index) => {
      item.id = index;
    });
    this.setData({ demoList, y0: 0 });
  },
})
